# coding=utf-8

from .config import secret,webhook_url
import json
import requests
import time
import hashlib
import base64
import urllib.parse
import hmac
from datetime import datetime

def send_dingtalk_markdown(title, text):
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    headers = {
        "Content-Type": "application/json"
    }
    
    # 构建Markdown消息内容
    markdown_msg = {
        "msgtype": "markdown",
        "markdown": {
            "title": title,
            "text": text+"\n\n"+getTime()
        }
    }
    url = f'{webhook_url}&timestamp={timestamp}&sign={sign}'

    # 发送请求
    response = requests.post(url, headers=headers, data=json.dumps(markdown_msg))
    return response.json()


def getTime():
    # 获取当前时间
    now = datetime.now()
    
    # 格式化时间为“年月日时分秒”的格式
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
    
    # 输出格式化后的时间
    return formatted_time

# 示例调用
if __name__ == "__main__":
    title = "项目进展报告"
    text = "### 项目进展\n\n任务1：完成 70%\n\n任务2：待处理\n\n- 列表项1\n- 列表项2\n\n"
    result = send_dingtalk_markdown(title, text)
    print(result)